import { VISIT_META_KEY, VISIT_RIGHTS } from '@/decorators/visit.decorator';
import { Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private reflector: Reflector) {
    super();
  }

  canActivate(context: any) {
    const visitRights = this.reflector.getAllAndOverride(VISIT_META_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (visitRights === VISIT_RIGHTS.NOT_ALL_PUBLIC) {
      if (context.args[0].headers.authorization) {
        return super.canActivate(context);
      } else {
        return true;
      }
    }

    if (visitRights === VISIT_RIGHTS.PUBLIC) return true;
    return super.canActivate(context);
  }
}
